/* Copyright 2014 Jan Wolter */
#include "stack.h"
#include "tableau.h"
#include "found.h"
#include "course.h"
#include "stock.h"
#include "solve.h"
#include "game.h"

#define COMPRESS_STATE

char *gamename= "All In A Row";
char *gameopt= "IR";
Stack *gathered= NULL;
Stack *temp= NULL;

int nplayed= 0;
int nwon= 0;
int nabandoned= 0;
int cardsleft= 0;
int maxoff;

int invert= 0;
int byrow= 0;

void setopt(char c)
{
    switch (c)
    {
	case 'I': invert= 1; break;
	case 'R': byrow= 1; break;	/* Deal by row instead of col */
    }
}


/* This is the main program for setting up the current game */
void exec(int gather, int arif, int over, int cut)
{
    /* Could set things like ndeck, nsuit here */

    /* Build and shuffle the deck */
    Stack *shuf= mixcards(arif, over, cut);

    /* Create the waste/foundation thingy */
    makeCourse(1,1,NULL);

    /* Create the tableau */
    for (int i= 1; i <= 13; i++)
	makeTableau(byrow ? 0 : 4, FLIP_NONE, shuf,
	    S_NONE, 0, S_NONE, 0, 1, F_NONE, BREAK_NOWHERE, 0);

    if (byrow)
    {
	for (int j= 0; j < 4; j++)
	    for (int i= 0; i < 13; i++)
	    {
		Card *c= popStack(shuf);
		if (c == NULL) break;
		pushStack(stacks+tableau[i].id, c);
	    }
    }


    if (invert)
    {
	for (int i= 0; i < 13; i++)
	{
	    Stack *s= stacks + tableau[i].id;

	    Card *c= s->c[0]; s->c[0]= s->c[3]; s->c[3]= c;
	    c= s->c[1]; s->c[1]= s->c[2]; s->c[2]= c;
	}
    }

    freeStack(shuf);

    if (verbose > 1) printState(stdout, stacks);

    maxoff= 0;
    int win= solve(gather,0);

    if (verbose > 0) printf("maxoff=%d\n",maxoff);
    nplayed++;
    cardsleft+= maxoff;
    if (win == 1)
	nwon++;
    else if (win == 2)
	nabandoned++;

    cleanFound();
    cleanTableau();
    cleanCourse();
    cleanStacks();
    cleanVisited();
}

void gatherAll()
{
    if (gathered == NULL)
	gathered= allocStack(ncard);
    else
	gathered->n= 0;

    gatherTableau(gathered);
    gatherCourse(gathered,0);
    if (gathered->n != ncard)
    {
	printf("Gather Failed - found %d cards\n",gathered->n);
	exit(1);
    }
}

/* How good is a move? Returns 0 if the move is completely safe and should
 * be made immediately without counting this position a choice point for
 * backtracking. Positive values are lower for better moves. Negative values
 * mean the move should not be done at all.
 */
int rateMove(Stack *src, int index1, int len, Stack *dst)
{
    CourseStack *c= course + dst->tid;
    int dirscore= 30;

    /* Don't consider removing cards from one-card stacks if there are
     * multi-card stacks with a card of the same rank on top, or if there
     * is a earlier one-card stack with a card of the same rank.
     */
    if (src->n == 1)
    {
	int newpip= src->c[index1]->n;
	for (int k= 0; k < ntableau; k++)
	{
	    Stack *s= stacks + tableau[k].id;
	    if (src == s || s->n == 0 || topStack(s)->n != newpip)
		continue;
	    if (s->n > 1 || s < src)
		return -1;
	}
    }

    /* Prefer NOT making a direction change */
    if (dst->n > 2)
    {
	int newpip= src->c[index1]->n;
	int toppip= dst->c[dst->n-1]->n;
	int nxtpip= dst->c[dst->n-2]->n;

	int olddir= (toppip-nxtpip + 13)%13;
	int newdir= (newpip-toppip + 13)%13;
	if (olddir != newdir) dirscore= 60;
    }

    /* Otherwise, prefer cards from taller stacks */
    return dirscore - src->n;
}

void printState(FILE *f, Stack *stks)
{
    printFound(f, stks);
    printTableau(f, stks);
    printCourse(f, stks);
}

int victory()
{
    int off= nOff();
    if (off > maxoff) maxoff= off;
    return (off == ncard);
}

/* Return a quality rating for the current solution. Bigger is better. Usually
 * it's just cards off. This is used to decide which solution to report in
 * cases where we never win.
 */
int quality()
{
    return nOff();
}

void summary()
{
    printf("Played:    %d games\n",nplayed);
    printf("Won:       %d games (%.2f%)\n",nwon,(float)nwon*100/nplayed);
    printf("Abandoned: %d games (%.2f%)\n",nabandoned,(float)nabandoned*100/nplayed);
    printf("Cards Off: %.2f\n",(float)cardsleft/nplayed);
}

/* Return a string that uniquely describes the current state. */
char *currstate()
{
    /* card count for each tableau stack, and top card on course */
    char buf[ntableau+10], *p= buf;

    /* Numbers of cards in each tableau pile */
    /* We add one to each count because we don't want any zeros */
#ifdef COMPRESS_STATE
    /* Assumes that all stack sizes are between 0 and 7 */
    int k;
    for (k= 0; k < ntableau - 1; k+= 2)
	*(p++)= (stacks[tableau[k].id].n << 1) +
	        (stacks[tableau[k+1].id].n << 4) + 1;
    if (k == ntableau - 1)
	*(p++)= stacks[tableau[k].id].n + 1;
#else
    for (int k= 0; k < ntableau; k++)
	*(p++)= stacks[tableau[k].id].n + 1;
#endif

    /* Pip value of top card on course */
    Stack *fs= stacks + course[0].id;
    if (fs->n > 0)
	*(p++)= fs->c[fs->n-1]->n;

    *p= '\0';

    return strdup(buf);
}
